package com.runen.wnhz.runen.ui.fragment.minem;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.Image;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.runen.wnhz.runen.R;
import com.runen.wnhz.runen.common.utils.ACacheUtlis;
import com.runen.wnhz.runen.common.utils.Constants;
import com.runen.wnhz.runen.common.utils.JumpUtlis;
import com.runen.wnhz.runen.common.utils.ToastUtil;
import com.runen.wnhz.runen.data.entity.ArticleEntity;
import com.runen.wnhz.runen.data.entity.ArticleListEntity;
import com.runen.wnhz.runen.data.entity.HomeBannerBean;
import com.runen.wnhz.runen.data.entity.LessonListEntity;
import com.runen.wnhz.runen.data.entity.ShopTypeEntity;
import com.runen.wnhz.runen.data.entity.UserBean;
import com.runen.wnhz.runen.di.component.ApplicationComponent;
import com.runen.wnhz.runen.di.component.DaggerHomeComponent;
import com.runen.wnhz.runen.di.module.HomeMdule;
import com.runen.wnhz.runen.presenter.Contart.HomeContart;
import com.runen.wnhz.runen.presenter.iPresenter.IhomePersenter;
import com.runen.wnhz.runen.ui.activity.WebViewActivity;
import com.runen.wnhz.runen.ui.activity.main.MainActivity;
import com.runen.wnhz.runen.ui.activity.main.SearchActivity;
import com.runen.wnhz.runen.ui.activity.main.SearchResultActivity;
import com.runen.wnhz.runen.ui.activity.major.ArticleListActivity;
import com.runen.wnhz.runen.ui.activity.major.CourseDetailsActivity;
import com.runen.wnhz.runen.ui.activity.major.IntroductionActivity;
import com.runen.wnhz.runen.ui.adapter.puadapter.LessonHomeAdapter;
import com.runen.wnhz.runen.ui.adapter.puadapter.ShopTypeAdapter;
import com.runen.wnhz.runen.ui.adapter.puadapter.ZiliaoHomeAdapter;
import com.runen.wnhz.runen.ui.fragment.BaseFragment;
import com.runen.wnhz.runen.widget.TitleBuilder;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.bean.ZxingConfig;
import com.yzq.zxinglibrary.common.Constant;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;

/**
 * Created by Administrator on 2018-04-08.
 */

public class HomeFragment extends BaseFragment<IhomePersenter> implements View.OnClickListener, HomeContart.View {

    @BindView(R.id.convenientBanner)
    Banner banner;
    @BindView(R.id.tv_shuo_title)
    TextView tv_shuo_title;

    @BindView(R.id.tv_shuo_view)
    TextView tv_shuo_view;

    @BindView(R.id.tv_tushuo)
    TextView tv_tushuo;

    @BindView(R.id.iv_tushuo)
    ImageView iv_tushuo;

    @BindView(R.id.ry_tushuo)
    RelativeLayout relativeLayout;

    @BindView(R.id.ry_Forum)
    RecyclerView rvLesson;

    @BindView(R.id.ry_ziliaojingxuan)
    RecyclerView rvZiliao;

    @BindView(R.id.ry_data_service)
    RecyclerView rvDataService;

    @BindView(R.id.img_sao)
    ImageView img_sao;


    private ArrayList<String> list_path = new ArrayList<>();
    private ArrayList<String> list_title = new ArrayList<>();

    public static final String TAG = "HomeFragment";


    @Override
    public void setupAcitivtyComponent(ApplicationComponent appComponent) {
        DaggerHomeComponent.builder()
                .applicationComponent(appComponent)
                .homeMdule(new HomeMdule(this))
                .build().initject(this);

    }

    @Override
    protected int getLayoutView() {
        return R.layout.home_fragment_layout;
    }

    @Override
    public void initUiAndListener(View view) {

    }

    @Override
    protected void init() {
        UserBean reqeustUser = ACacheUtlis.getInstance().getReqeustUser(getContext());
//        Log.e(TAG, "init: " + reqeustUser.toString());
        mPresenter.getBannerData();
        mPresenter.getImageSay();
        mPresenter.getLessonList(1, 0, 10);
        mPresenter.getZiliaoList(3, 0, 10);
        mPresenter.getShopTypeList();
        initLinClick();
        initView();
    }

    private void initView() {

    }


    @Override
    protected void baseInit() {
        super.baseInit();

    }

    @Override
    public void initToolBar(TitleBuilder mTitleBuilder) {
        setToolBarVisible(View.GONE);
    }

    private void initLinClick() {

        relativeLayout.setOnClickListener(this);

    }

    /**
     * 初始化banner
     */


    @Override
    @OnClick({R.id.rl_allClassroom, R.id.rl_ziliaojingxuan, R.id.ry_tushuo, R.id.rl_serach, R.id.et_search,R.id.img_sao})
    public void onClick(View view) {
        switch (view.getId()) {
            //跳转到详情界面
            case R.id.ry_tushuo:
                JumpUtlis.getInstance().jumpActivity(getActivity(), ArticleListActivity.class);
                break;
            case R.id.rl_allClassroom:
                MainActivity mainActivity = (MainActivity) getActivity();
                mainActivity.goToFragment(1);
                EventBus.getDefault().post(1, "rbSelected");
                break;
            case R.id.rl_ziliaojingxuan:
                Intent intent2 = new Intent(getActivity(),SearchResultActivity.class);
                intent2.putExtra("so","");
                intent2.putExtra("type","3");
                startActivity(intent2);
                break;
            //跳转搜索页面
            case R.id.et_search:
            case R.id.rl_serach:
                JumpUtlis.getInstance().jumpActivity(getActivity(), SearchActivity.class);
                break;
            case R.id.img_sao:

               if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
                  ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
                Intent intent = new Intent(getActivity(), CaptureActivity.class);
                ZxingConfig config = new ZxingConfig();
                config.setPlayBeep(true);
                config.setShake(true);
                intent.putExtra(Constant.INTENT_ZXING_CONFIG,config);
                startActivityForResult(intent,1);
                break;

        }
    }


        @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 摄像头权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
//                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(getActivity(), "请至权限中心打开本应用的相机访问权限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        if (requestCode == 1 && resultCode == RESULT_OK) {
            if (data != null) {

                String content = data.getStringExtra(Constant.CODED_CONTENT);
                ToastUtil.showToast("扫描结果为："+content);
                String[] getVal = content.split(";");
                String type  = getVal[2];
                String[] getTypeVal = type.split("=");
                Intent intent2 = new Intent(getActivity(),SearchResultActivity.class);
                intent2.putExtra("so","");
                intent2.putExtra("type",getTypeVal[1]);
                startActivity(intent2);
//                result.setText("扫描结果为：" + content);
            }
        }
    }

    @Override
    public void showLoadding() {

    }

    @Override
    public void dimissLoding() {

    }

    @Override
    public void showErrorMessage(String msg) {

    }

    @Override
    public void onTitleButtonClicked(TitleBuilder.TitleButton clicked) {

    }

    /*跳转类型  1.article 文章 2.lesson 课程
     *         .url => 跳转地址  1.文章tid  2.课程lid
     *         0.img        => 展示图片*/
    @Override
    public void getBannerRequest(final List<HomeBannerBean> bannerDatas) {
        Log.e("----1111", bannerDatas.size() + "");
        for (int i = 0; i < bannerDatas.size(); i++) {
            list_path.add(bannerDatas.get(i).getImg());
            list_title.add(bannerDatas.get(i).getUrl());

            //设置内置样式，共有六种可以点入方法内逐一体验使用。
            banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
            //设置图片加载器，图片加载器在下方
            banner.setImageLoader(new MyLoader());
            //设置图片网址或地址的集合
            banner.setImages(list_path);
            //设置轮播的动画效果，内含多种特效，可点入方法内查找后内逐一体验
            banner.setBannerAnimation(Transformer.Default);
            //设置轮播图的标题集合
            banner.setBannerTitles(list_title);
            //设置轮播间隔时间
            banner.setDelayTime(3000);
            //设置是否为自动轮播，默认是“是”。
            banner.isAutoPlay(true);
            //设置指示器的位置，小点点，左中右。
            banner.setIndicatorGravity(BannerConfig.CENTER);
            banner.setOnBannerListener(new OnBannerListener() {
                @Override
                public void OnBannerClick(int position) {
                    HomeBannerBean homeBannerBean = bannerDatas.get(position);
                    bannerStartJudge(homeBannerBean);
                }
            });
            //必须最后调用的方法，启动轮播图。
            banner.start();
        }
    }

    private void bannerStartJudge(HomeBannerBean homeBannerBean){
        Intent intent = new Intent();
        if("lesson".equals(homeBannerBean.getUrl_type())){
            intent.setClass(getActivity(),CourseDetailsActivity.class);
            intent.putExtra("lid",homeBannerBean.getUrl());
        }else if("article".equals(homeBannerBean.getUrl_type())){
            Bundle bundle = new Bundle();
            bundle.putString("url", Constants.BaseUrl + "Article_articleInfo/tid/" + homeBannerBean.getUrl());
            bundle.putString("title", "图说详情");
            intent.setClass(getActivity(),WebViewActivity.class);
            intent.putExtra("url", Constants.BaseUrl + "Article_articleInfo/tid/" + homeBannerBean.getUrl());
            intent.putExtra("title", "图说详情");
        }
        startActivity(intent);
    }


    /**
     * return string re    =>1
     *
     * @return string data.des  =>描述
     */
    @Override
    public void getArticleRequest(ArticleEntity artleDatas) {
        String Fid = artleDatas.getFid();
        Glide.with(getContext()).load(artleDatas.getForm_img().replace("&amp;", "&")).into(iv_tushuo);
        tv_shuo_view.setText(artleDatas.getViews() + "人阅读");
        tv_tushuo.setText(artleDatas.getForm_title());
        tv_shuo_title.setText(artleDatas.getDes());
    }

    @Override
    public void getArticleListRequest(ArticleListEntity articleListDatas) {

    }

    @Override
    public void getLessonListRequest(LessonListEntity lessonList) {

        if (lessonList.getList().size() > 4) {
            List<LessonListEntity.ListBean> list = new ArrayList<>();
            for (int i = 0; i < 4; i++) {
                list.add(lessonList.getList().get(i));
            }
            lessonList.setList(list);
        }

        LessonHomeAdapter adapter = new LessonHomeAdapter(getContext(), lessonList, true);
        GridLayoutManager manager = new GridLayoutManager(getActivity(), 2);
        rvLesson.setLayoutManager(manager);
        rvLesson.setAdapter(adapter);

        adapter.setItemClickListener(new LessonHomeAdapter.MyItemClickListener() {
            @Override
            public void onItemClick(View view, LessonListEntity.ListBean lessonEntity) {
                Log.e("----onItemClick", lessonEntity.toString());
                Bundle bundle = new Bundle();
                bundle.putString(CourseDetailsActivity.LID, lessonEntity.getLid());
                JumpUtlis.getInstance().jumpActivity(getActivity(), CourseDetailsActivity.class, bundle);
            }
        });
    }

    @Override
    public void getZiliaoListRequest(LessonListEntity lessonList) {

        if (lessonList.getList().size() > 6) {
            List<LessonListEntity.ListBean> list = new ArrayList<>();
            for (int i = 0; i < 6; i++) {
                list.add(lessonList.getList().get(i));
            }
            lessonList.setList(list);
        }

        ZiliaoHomeAdapter adapter = new ZiliaoHomeAdapter(getContext(), lessonList);
        GridLayoutManager manager = new GridLayoutManager(getActivity(), 3);
        rvZiliao.setLayoutManager(manager);
        rvZiliao.setAdapter(adapter);

        adapter.setItemClickListener(new ZiliaoHomeAdapter.MyItemClickListener() {
            @Override
            public void onItemClick(View view, LessonListEntity.ListBean lessonEntity) {
                Log.e("----onItemClick", lessonEntity.toString());

                Bundle bundle = new Bundle();
                bundle.putString("pic", lessonEntity.getPic());
                bundle.putString("lid", lessonEntity.getLid());
                JumpUtlis.getInstance().jumpActivity(getActivity(), IntroductionActivity.class, bundle);
            }
        });
    }

    @Override
    public void getShopTypeRequest(List<ShopTypeEntity> shopTypeEntityList) {

        ShopTypeAdapter adapter = new ShopTypeAdapter(getContext(), shopTypeEntityList);
        GridLayoutManager manager = new GridLayoutManager(getActivity(), 3);
        rvDataService.setLayoutManager(manager);
        rvDataService.setAdapter(adapter);

        adapter.setItemClickListener(new ShopTypeAdapter.MyItemClickListener() {
            @Override
            public void onItemClick(View view, ShopTypeEntity shopTypeEntity) {
                Log.e("----onItemClick", shopTypeEntity.toString());

                EventBus.getDefault().post(shopTypeEntity.getId(), "shopType");
                EventBus.getDefault().post(2, "rbSelected");
                MainActivity mainActivity = (MainActivity) getActivity();
                mainActivity.goToFragment(2);
            }
        });
    }

    //自定义的图片加载器
    private class MyLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            Glide.with(context).load((String) path).into(imageView);
        }
    }
}
